package hp.com.servlet.CartDataServlet;

import hp.com.entity.CartData;
import hp.com.entity.Users;
import hp.com.service.CartDataService;
import hp.com.service.impl.CartDataServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/AddToCart")
public class AddToCart extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CartDataService cs = new CartDataServiceImpl();
        //从js中获取suk，并转换成与数据库相同的格式
        String suk = (String)req.getParameter("suk").replace(",","|");
        int userId = 0;
        try{
            //从session中获取UserId
             userId =((Users)(req.getSession().getAttribute("userSession"))).getId();
        }catch (NullPointerException e){
            //如果未登录，则跳转到登录界面
            resp.getWriter().print("login");
            resp.sendRedirect(req.getContextPath()+"/jbs/Login.jsp");
            return;
        }
        //获取其他的参数数据
        int amount =Integer.parseInt( req.getParameter("amount"));
        int itemId = Integer.parseInt(req.getParameter("id"));
        CartData cart = new CartData();
        try{
            cart=cs.getCartData(itemId,userId,suk,amount);
            cs.AddToCart(cart);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        resp.getWriter().print("success");
    }
}
